﻿' ----------------------------------------------------------------------------------------
' Author:                    Diego
' Company:                   
' Assembly version:          1.0.0.0
' Date:                      02/10/2010
' Time:                      15:27
' Solution Name:             SistemaRC
' Solution Filename:         SistemaRC.sln
' Solution FullFilename:     C:\SistemaRC\SistemaRC\SistemaRC.sln
' Project Name:              SistemaRC
' Project Filename:          SistemaRC.vbproj
' Project FullFilename:      C:\SistemaRC\SistemaRC\SistemaRC\SistemaRC.vbproj
' Project Item Name:         FrmPedidosN
' Project Item Filename:     FrmPedidosN.vb
' Project Item FullFilename: C:\SistemaRC\SistemaRC\SistemaRC\Forms\FrmPedidosN.vb
' Project Item Kind:         Formulario
' Purpose:                   inhabilitar
' ----------------------------------------------------------------------------------------
Imports System.Data.SqlClient
Imports System.IO
Imports System.Xml
Imports System.Data
Imports Microsoft.Win32
Imports Microsoft.ReportingServices
Imports Microsoft.Reporting.WinForms

Public Class FrmPedidosN

    Dim controller As New Class_RC_Controller.rc_Notas
    Dim clientes As New Class_RC_Controller.rc_Clientes
    Dim productos As New Class_RC_Controller.rc_Productos
    Dim servicios As New Class_RC_Controller.rc_Servicios

    Private _codNota As Integer = 0

    Public Property codNota() As Integer
        Get
            Return _codNota
        End Get
        Set(value As Integer)
            _codNota = value
        End Set
    End Property

    Private _codCliente As Integer = 0

    Public Property codCliente() As Integer
        Get
            Return _codCliente
        End Get
        Set(value As Integer)
            _codCliente = value
        End Set
    End Property

    Private _codTipoEmp As Integer = 0

    Public Property codTipoEmp() As Integer
        Get
            Return _codTipoEmp
        End Get
        Set(value As Integer)
            _codTipoEmp = value
        End Set
    End Property

    Private Sub llenarCombos_ContactosCliente()
        If codCliente > 0 Then
            Dim dsCliente As DataTable
            dsCliente = clientes.get_Clientes_Contactos_All(oiml.dbConn, codCliente)
            If Not dsCliente Is Nothing Then
                With Me.cboContactos
                    .DataSource = dsCliente
                    .DisplayMember = "nombre"
                    .ValueMember = "codContacto"
                End With

            Else
                cboContactos.DataSource = Nothing

            End If

        Else
            cboContactos.DataSource = Nothing

        End If

    End Sub

    Private Sub llenarCombos_Actividad()
        If (IsNumeric(cboProducto.SelectedValue)) Then
            Dim dsA As DataTable
            dsA = controller.get_actividad_producto(oiml.dbConn, cboProducto.SelectedValue, 0)
            If Not dsA Is Nothing Then
                With Me.cboActividad
                    .DataSource = dsA
                    .DisplayMember = "descActividad"
                    .ValueMember = "codActividad"
                End With

                llenarCombos_Responsable()
                llenarCombos_Sector()

            Else
                Me.cboActividad.DataSource = Nothing
                Me.cboResponsable.DataSource = Nothing
                Me.cboSector.DataSource = Nothing
                Me.cboArea.DataSource = Nothing

            End If

        Else
            Me.cboActividad.DataSource = Nothing
            Me.cboResponsable.DataSource = Nothing
            Me.cboSector.DataSource = Nothing
            Me.cboArea.DataSource = Nothing

        End If

    End Sub

    Private Sub llenarCombos_Responsable()
        If (IsNumeric(cboActividad.SelectedValue)) Then
            Dim dsRespon As DataTable
            dsRespon = controller.get_responsable_actividad_notas(oiml.dbConn, cboActividad.SelectedValue)
            If Not dsRespon Is Nothing Then
                With Me.cboResponsable
                    .DataSource = dsRespon
                    .DisplayMember = "empleado"
                    .ValueMember = "codEmp"
                End With

            Else
                cboResponsable.DataSource = Nothing

            End If

        End If

    End Sub

    Private Sub llenarCombos_Sector()

        If (IsNumeric(cboActividad.SelectedValue)) Then
            Dim dsSector As DataTable
            dsSector = controller.get_sector_actividad(oiml.dbConn, cboActividad.SelectedValue)
            If Not dsSector Is Nothing Then
                With Me.cboSector
                    .DataSource = dsSector
                    .DisplayMember = "descSector"
                    .ValueMember = "codSector"
                End With

                llenarCombos_Areas()

            Else
                cboSector.DataSource = Nothing
                cboArea.DataSource = Nothing

            End If

        Else
            cboArea.DataSource = Nothing

        End If

    End Sub

    Private Sub llenarCombos_Areas()

        If (IsNumeric(cboSector.SelectedValue)) Then
            Dim dsA As DataTable
            dsA = controller.get_area_sector(oiml.dbConn, cboSector.SelectedValue)
            If Not dsA Is Nothing Then
                With Me.cboArea
                    .DataSource = dsA
                    .DisplayMember = "descArea"
                    .ValueMember = "codArea"
                End With
            Else

                cboArea.DataSource = Nothing

            End If

        End If

    End Sub

    Private Sub llenarCombosEstado(codEstadoFinalizado As Integer)
        Dim ds As DataTable
        ds = controller.get_estado_notas(oiml.dbConn, codEstadoFinalizado)
        With cboEstado
            .DataSource = ds
            .DisplayMember = "descEstadoNota"
            .ValueMember = "codEstadoNota"
        End With
    End Sub

    Private Sub llenarCombos()

        Me.cboIVA.SelectedIndex = 2
        Me.cboIvaServicio.SelectedIndex = 2

        llenarCombosEstado(oiml.codEstadoCierreNota)

        Dim dsTipo As DataTable
        dsTipo = productos.get_tipo_Productos(oiml.dbConn)
        With Me.cboTipoProducto
            .DataSource = dsTipo
            .DisplayMember = "descTipoProducto"
            .ValueMember = "codTipoProducto"
        End With

        Dim dsTipoSer As DataTable
        dsTipoSer = productos.get_tipo_Servicios(oiml.dbConn)
        With Me.cboTipoServicio
            .DataSource = dsTipoSer
            .DisplayMember = "descTipoServicio"
            .ValueMember = "codTipoServicio"
        End With

        Dim dsEmpl As DataTable
        dsEmpl = productos.get_empleados(oiml.dbConn)
        With Me.cboResponsableServicio
            .DataSource = dsEmpl
            .DisplayMember = "empleado"
            .ValueMember = "codEmp"
        End With

        CargarProductos()

        cboEstadoAct.SelectedIndex = 0
        cboEstadoServicio.SelectedIndex = 0

    End Sub

    Private Sub CargarProductos()

        Dim codTipoProducto As Integer = 0

        If cbxTipo.Checked And IsNumeric(cboTipoProducto.SelectedValue) Then
            codTipoProducto = cboTipoProducto.SelectedValue
        End If

        Dim dt As New DataTable
        dt = productos.get_Productos_All(oiml.dbConn, 0, txtProducto.Text, codTipoProducto, True)
        If Not dt Is Nothing Then

            With Me.cboProducto
                .DataSource = dt
                .DisplayMember = "DescProducto"
                .ValueMember = "codProducto"
            End With

            SeleccionarProducto()

        Else

            cboProducto.DataSource = Nothing
            txtPrecio.Text = 0
            cboActividad.DataSource = Nothing
            cboSector.DataSource = Nothing
            cboArea.DataSource = Nothing
            cboResponsable.DataSource = Nothing

        End If

    End Sub

    Private Sub CargarServicios()

        Dim codTipoServicio As Integer = 0

        If cbxTipoServicio.Checked And IsNumeric(cboTipoServicio.SelectedValue) Then
            codTipoServicio = cboTipoServicio.SelectedValue
        End If

        Dim dt As New DataTable
        dt = servicios.get_Servicios_All(oiml.dbConn, 0, txtServicio.Text, codTipoServicio, True)
        If Not dt Is Nothing Then

            With Me.cboServicio
                .DataSource = dt
                .DisplayMember = "descripcion"
                .ValueMember = "codServicio"
            End With

            If IsNumeric(cboServicio.SelectedValue) Then
                CargarServicios_ByID(Integer.Parse(cboServicio.SelectedValue))
            End If

        Else

            cboServicio.DataSource = Nothing
            txtPrecioServicio.Text = 0
            cboResponsableServicio.DataSource = Nothing

        End If

    End Sub

    Private Sub CargarDetalles()
        If codNota > 0 Then

            Dim dt As New DataTable
            dt = controller.get_Notas_Detalles_All(oiml.dbConn, codNota, False, False, False)
            If Not dt Is Nothing Then
                dgNotasDetalle.DataSource = dt

            End If

        End If

    End Sub

    Private Sub CargarNota()
        Try
            If codNota > 0 Then

                Dim ds As New DataTable
                ds = controller.get_Notas_ByID(oiml.dbConn, codNota)

                If Not ds Is Nothing Then

                    ' cargar los controles del formulario con los valores de los campos del registro
                    codNota = ds.Rows(0)("codNota").ToString
                    Me.txtNro.Text = ds.Rows(0)("nroNota").ToString
                    Me.dtpfecha.Value = DateTime.Parse(ds.Rows(0)("fecha").ToString())
                    Me.dtpfechaVto.Value = DateTime.Parse(ds.Rows(0)("fechaVencimiento").ToString())
                    Me.cboEstado.SelectedValue = ds.Rows(0)("codEstadoNota").ToString

                    If Me.cboEstado.SelectedValue = oiml.codEstadoAnulaNota Then

                        gbrdetalle.Enabled = False
                        gbrdetalle.Visible = False
                        grpControles.Enabled = False
                        grbdatosclientes.Enabled = False
                        gbrdatospedido.Enabled = False

                    ElseIf Integer.Parse(ds.Rows(0)("codEstadoNota").ToString) = oiml.codEstadoCierreNota Then

                        llenarCombosEstado(0)
                        Me.cboEstado.SelectedValue = ds.Rows(0)("codEstadoNota").ToString

                        gbrdetalle.Enabled = False
                        gbrdetalle.Visible = False
                        grpControles.Enabled = False
                        grbdatosclientes.Enabled = False
                        gbrdatospedido.Enabled = False

                    End If

                    If ds.Rows(0)("totalDetalle").ToString() <> "" Then
                        Me.txtTotal.Text = Decimal.Parse(ds.Rows(0)("totalDetalle").ToString()).ToString("N0")
                    Else
                        Me.txtTotal.Text = 0
                    End If

                    codCliente = ds.Rows(0)("codCliente").ToString()
                    Me.txtNombre.Text = ds.Rows(0)("nombre").ToString & " - " & ds.Rows(0)("ruc").ToString
                    Me.cboContactos.SelectedValue = ds.Rows(0)("codContacto").ToString
                    Me.txtRUC.Text = ds.Rows(0)("ruc").ToString
                    Me.txtTelefono.Text = ds.Rows(0)("celular").ToString
                    Me.txtdireccion.Text = ds.Rows(0)("direccion").ToString
                    Me.lblUsuario.Text = ds.Rows(0)("usuario").ToString
                    Me.lblfechaActualizacion.Text = ds.Rows(0)("fechaActualizacion_").ToString

                    CargarDetalles()
                    'ControlEstado()

                End If

            Else

                ' cargar los controles del formulario con los valores de los campos del registro
                codNota = 0

                Me.txtNro.Text = ""
                Me.dtpfecha.Value = DateTime.Now
                Me.dtpfechaVto.Value = DateTime.Now

                Me.txtTotal.Text = 0
                Me.txtNombre.Text = ""

                Me.txtRUC.Text = ""
                Me.txtTelefono.Text = ""
                Me.txtdireccion.Text = ""

                lblUsuario.Text = oiml.Usuario
                lblfechaActualizacion.Text = Date.Now.ToShortDateString

                dtpfecha.Focus()

            End If

        Catch ex As Exception
            MessageBox.Show("Error: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)

        End Try

    End Sub

    'Private Sub ControlEstado()
    '    If Me.cboEstado.Text = "APROBADA" Or Me.cboEstado.Text = "ANULADA" Then
    '        grbCabecera.Enabled = False
    '        grbDetalle.Enabled = False
    '    Else

    '        If controller.Update_Ventas(oiml.dbConn, codVenta, nroFactura.Text, fechaFactura.Value, "", cboTipo.Text, cboEstado.Text,
    '                                    Decimal.Parse(txtTotalFactura.Text), Decimal.Parse(txtSaldo.Text), Decimal.Parse(txtIVA.Text), cboCliente.SelectedValue,
    '                                    cboVendedor.SelectedValue, oiml.idUsuario) = False Then
    '            MessageBox.Show("Error: " & controller.MessageError.Message, "Ventas", MessageBoxButtons.OK, MessageBoxIcon.Error)
    '            Exit Sub
    '        End If

    '    End If
    'End Sub

    Private Shadows Sub KeyUpmask(ByVal MaskedTextboxs As System.Windows.Forms.MaskedTextBox, ByVal e As System.Windows.Forms.KeyEventArgs)

        'Teclas que Utilizaremos El cual solo son las numericas
        If e.KeyData = Keys.Space Or e.KeyData = Keys.Decimal Or _
         e.KeyData = Keys.NumPad0 Or e.KeyData = Keys.NumPad1 Or e.KeyData = Keys.NumPad2 Or e.KeyData = Keys.NumPad3 _
           Or e.KeyData = Keys.NumPad4 Or e.KeyData = Keys.NumPad5 Or e.KeyData = Keys.NumPad6 Or _
           e.KeyData = Keys.NumPad7 Or e.KeyData = Keys.NumPad8 Or e.KeyData = Keys.NumPad9 _
           Or e.KeyData = Keys.D0 Or e.KeyData = Keys.D1 Or e.KeyData = Keys.D2 Or e.KeyData = Keys.D3 Or _
           e.KeyData = Keys.D4 Or e.KeyData = Keys.D5 Or e.KeyData = Keys.D6 _
           Or e.KeyData = Keys.D7 Or e.KeyData = Keys.D8 Or e.KeyData = Keys.D9 Or e.KeyData = Keys.Tab Or e.KeyData = Keys.Enter _
            Then

            'Programamos la tecla de Retroceso en el textbox
        ElseIf e.KeyData = Keys.Back And MaskedTextboxs.Text.Length > 0 Then
            On Error Resume Next
            'Removemos un caracter mediante se presione la tecla Back
            MaskedTextboxs.Text.Remove(MaskedTextboxs.SelectionStart - 1)

            'si el textbox es menor que un caracter
        ElseIf MaskedTextboxs.Text.Length < 1 Then
            'ponemos el textbox En Blanco
            MaskedTextboxs.Text = String.Empty
            'ponemos la variable    NumerosYaescritos en Blanco

        Else
            'ponemos el textbox enblanco
            MaskedTextboxs.Text = String.Empty
            'Hacemos Sonar un Beep para indicarle al usuario que ha presionado un caracter y no un Numero
            Beep()
            MsgBox("Introducir solo valores numericos")
        End If

    End Sub

    Private Shadows Sub KeyUp(ByVal TextBoxs As System.Windows.Forms.TextBox, ByVal e As System.Windows.Forms.KeyEventArgs)

        'Teclas que Utilizaremos El cual solo son las numericas
        If e.KeyData = Keys.Space Or e.KeyData = Keys.Decimal Or _
         e.KeyData = Keys.NumPad0 Or e.KeyData = Keys.NumPad1 Or e.KeyData = Keys.NumPad2 Or e.KeyData = Keys.NumPad3 _
           Or e.KeyData = Keys.NumPad4 Or e.KeyData = Keys.NumPad5 Or e.KeyData = Keys.NumPad6 Or _
           e.KeyData = Keys.NumPad7 Or e.KeyData = Keys.NumPad8 Or e.KeyData = Keys.NumPad9 _
           Or e.KeyData = Keys.D0 Or e.KeyData = Keys.D1 Or e.KeyData = Keys.D2 Or e.KeyData = Keys.D3 Or _
           e.KeyData = Keys.D4 Or e.KeyData = Keys.D5 Or e.KeyData = Keys.D6 _
           Or e.KeyData = Keys.D7 Or e.KeyData = Keys.D8 Or e.KeyData = Keys.D9 Or e.KeyData = Keys.Tab Or e.KeyData = Keys.Enter _
           Or e.KeyData = Keys.OemMinus Then

            'Programamos la tecla de Retroceso en el textbox
        ElseIf e.KeyData = Keys.Back And TextBoxs.Text.Length > 0 Then
            On Error Resume Next
            'Removemos un caracter mediante se presione la tecla Back
            TextBoxs.Text.Remove(TextBoxs.SelectionStart - 1)

            'si el textbox es menor que un caracter
        ElseIf TextBoxs.Text.Length < 1 Then
            'ponemos el textbox En Blanco
            TextBoxs.Text = String.Empty
            'ponemos la variable    NumerosYaescritos en Blanco

        Else
            'ponemos el textbox enblanco
            TextBoxs.Text = String.Empty
            'Hacemos Sonar un Beep para indicarle al usuario que ha presionado un caracter y no un Numero
            Beep()
            MsgBox("Introducir solo valores numericos")
        End If

    End Sub

    Private Sub FrmPedidosN_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Me.dgNotasDetalle.AutoGenerateColumns = False
        Me.llenarCombos()
        Me.CargarNota()
    End Sub

    Private Function ValidarCampos() As Boolean

        Dim controlCampos As Boolean = False

        'If txtNro.Text = "" Then
        '    ErrorProvider.SetError(txtNro, "Campo obligatorio")
        '    controlCampos = True
        'Else
        '    ErrorProvider.SetError(txtNro, "")
        'End If

        If dtpfecha.Value.ToString = "" Then
            ErrorProvider.SetError(dtpfecha, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider.SetError(dtpfecha, "")
        End If

        If dtpfechaVto.Value.ToString = "" Then
            ErrorProvider.SetError(dtpfechaVto, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider.SetError(dtpfechaVto, "")
        End If

        If codCliente = 0 Then
            ErrorProvider.SetError(txtNombre, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider.SetError(txtNombre, "")
        End If
        '
        Return controlCampos

    End Function

    Private Function ValidarDetallesCampos() As Boolean

        Dim controlCampos As Boolean = False

        If IsNumeric(txtcantidad.Text) Then

            If Decimal.Parse(txtcantidad.Text) = 0 Then
                ErrorProvider.SetError(txtcantidad, "Campo cantidad mayor a cero.")
                controlCampos = True
            Else
                ErrorProvider.SetError(txtcantidad, "")
            End If        '

        Else
            ErrorProvider.SetError(txtcantidad, "Campo cantidad mayor a cero.")
            controlCampos = True
        End If

        If cboProducto.SelectedValue = 0 Then
            ErrorProvider.SetError(cboProducto, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider.SetError(cboProducto, "")
        End If

        'If cboActividad.SelectedValue = 0 Then
        '    ErrorProvider.SetError(cboActividad, "Campo obligatorio")
        '    controlCampos = True
        'Else
        '    ErrorProvider.SetError(cboActividad, "")
        'End If

        'If cboResponsable.SelectedValue = 0 Then
        '    ErrorProvider.SetError(cboResponsable, "Campo obligatorio")
        '    controlCampos = True
        'Else
        '    ErrorProvider.SetError(cboResponsable, "")
        'End If

        Return controlCampos

    End Function

    Private Function ValidarDetallesServicios() As Boolean

        Dim controlCampos As Boolean = False

        If IsNumeric(txtCantidadServicio.Text) Then

            If Decimal.Parse(txtCantidadServicio.Text) = 0 Then
                ErrorProvider.SetError(txtCantidadServicio, "Campo cantidad mayor a cero.")
                controlCampos = True
            Else
                ErrorProvider.SetError(txtCantidadServicio, "")
            End If        '

        Else
            ErrorProvider.SetError(txtCantidadServicio, "Campo cantidad mayor a cero.")
            controlCampos = True
        End If

        If cboServicio.SelectedValue = 0 Then
            ErrorProvider.SetError(cboServicio, "Campo obligatorio")
            controlCampos = True
        Else
            ErrorProvider.SetError(cboServicio, "")
        End If

        Return controlCampos

    End Function

    Private Sub btncancelar_Click(sender As System.Object, e As System.EventArgs) Handles btncancelar.Click
        Me.Close()
    End Sub

    Private Sub btnAgregarDetalle_Click(sender As System.Object, e As System.EventArgs) Handles btnAgregarProducto.Click
        Try

            If tabControl.SelectedIndex = 0 And ValidarDetallesCampos() Then
                MessageBox.Show("Falta llenar datos del detalle", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1)
                txtcantidad.Focus()

            ElseIf tabControl.SelectedIndex = 1 And ValidarDetallesServicios() Then
                MessageBox.Show("Falta llenar datos del detalle", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1)
                txtCantidadServicio.Focus()
            Else

                Dim obs As String

                If tabControl.SelectedTab.Name = "tabProducto" Then
                    obs = txtobs.Text
                Else
                    obs = txtObsServicio.Text
                End If

                If codNota = 0 Then

                    If ValidarCampos() Then
                        txtNro.Focus()
                        Exit Sub
                    Else

                        codNota = controller.Insert_Notas(oiml.dbConn, txtNro.Text, codCliente, dtpfecha.Value, cboEstado.SelectedValue, cboContactos.SelectedValue,
                                              Decimal.Parse(txtTotal.Text), 1, txtdireccion.Text, dtpfechaVto.Value, 0, obs, oiml.idUsuario)
                        If codNota = 0 Then
                            MessageBox.Show("Error: " & controller.MessageError.Message, "Pedidos", MessageBoxButtons.OK, MessageBoxIcon.Error)
                            Exit Sub
                        End If

                    End If

                Else

                    If ValidarCampos() Then
                        txtNro.Focus()
                        Exit Sub
                    Else

                        If controller.Update_Notas(oiml.dbConn, codNota, txtNro.Text, codCliente, dtpfecha.Value, cboEstado.SelectedValue, cboContactos.SelectedValue,
                                              Decimal.Parse(txtTotal.Text), 1, txtdireccion.Text, dtpfechaVto.Value, 0, obs, oiml.idUsuario) = False Then
                            MessageBox.Show("Error: " & controller.MessageError.Message, "Pedidos", MessageBoxButtons.OK, MessageBoxIcon.Error)
                            Exit Sub
                        End If

                    End If

                End If

                If codNota > 0 Then

                    Dim codProducto As Integer = 0
                    Dim codServicio As Integer = 0
                    Dim cantidad As Decimal = 0
                    Dim precio As Decimal = 0
                    Dim idActividad As Integer = 0
                    Dim idResponsable As Integer = 0
                    Dim estado As String = ""
                    Dim iva As Integer = 0


                    If tabControl.SelectedTab.Name = "tabProducto" Then
                        codProducto = Integer.Parse(cboProducto.SelectedValue)
                        cantidad = txtcantidad.Text
                        precio = txtPrecio.Text
                        idActividad = Integer.Parse(cboActividad.SelectedValue)
                        estado = cboEstadoAct.Text
                        idResponsable = Integer.Parse(cboResponsable.SelectedValue)

                        If cboIVA.Text.ToString = "05%" Then
                            iva = 5
                        ElseIf cboIVA.Text.ToString = "10%" Then
                            iva = 10
                        End If

                    Else
                        codServicio = Integer.Parse(cboServicio.SelectedValue)
                        cantidad = txtCantidadServicio.Text
                        precio = txtPrecioServicio.Text
                        estado = cboEstadoServicio.Text
                        idResponsable = Integer.Parse(cboResponsableServicio.SelectedValue)

                        If cboIvaServicio.Text.ToString = "05%" Then
                            iva = 5
                        ElseIf cboIvaServicio.Text.ToString = "10%" Then
                            iva = 10
                        Else
                            iva = 0
                        End If

                    End If

                    If controller.Insert_Notas_Detalle(oiml.dbConn, codNota, codProducto,
                                                       cantidad,
                                                       precio,
                                                       idActividad,
                                                       estado,
                                                       idResponsable,
                                                       codServicio, iva) Then
                        CargarNota()
                        limpiarDetalles()

                    Else
                        MessageBox.Show("Error: " & controller.MessageError.Message, "Pedidos", MessageBoxButtons.OK, MessageBoxIcon.Error)

                    End If

                End If

            End If

        Catch ex As Exception
            MsgBox(ex.Message)

        End Try

        txtcantidad.Text = 1

    End Sub

    Public Sub limpiarDetalles()
        txtcantidad.Text = 1
    End Sub

    Private Sub btnEliminarDetalle_Click(sender As System.Object, e As System.EventArgs) Handles btnEliminarDetalle.Click
        Try
            If dgNotasDetalle.SelectedRows.Count > 0 Then
                Dim codDetalle As Integer
                codDetalle = dgNotasDetalle.SelectedRows(0).Cells(0).Value

                If codDetalle > 0 And MessageBox.Show("Desea eliminar el registro seleccionado?", "Pedidos", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                    If controller.Delete_Notas_Detalle(oiml.dbConn, codDetalle) Then
                        CargarDetalles()
                    Else
                        MessageBox.Show("Error: " & controller.MessageError.Message, "Pedidos", MessageBoxButtons.OK, MessageBoxIcon.Error)

                    End If

                End If

            End If

        Catch ex As Exception
            MsgBox(ex.Message)

        End Try

    End Sub

    Private Sub btnGrabar_Click(sender As System.Object, e As System.EventArgs) Handles btnguardar.Click

        If ValidarCampos() Then
            txtNro.Focus()
            Exit Sub
        End If

        Dim obs As String

        If tabControl.SelectedTab.Name = "tabProducto" Then
            obs = txtobs.Text
        Else
            obs = txtObsServicio.Text
        End If

        If codNota = 0 Then

            codNota = controller.Insert_Notas(oiml.dbConn, txtNro.Text, codCliente, dtpfecha.Value, cboEstado.SelectedValue, cboContactos.SelectedValue,
                                              Decimal.Parse(txtTotal.Text), 1, txtdireccion.Text, dtpfechaVto.Value, 0, obs, oiml.idUsuario)

            If codNota > 0 Then
                MessageBox.Show("Registro grabado con exito!", "Pedidos", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                Me.DialogResult = Windows.Forms.DialogResult.OK
                CargarNota()

            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Pedidos", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End If

        Else
            If controller.Update_Notas(oiml.dbConn, codNota, txtNro.Text, codCliente, dtpfecha.Value, cboEstado.SelectedValue, cboContactos.SelectedValue,
                                              Decimal.Parse(txtTotal.Text), 1, txtdireccion.Text, dtpfechaVto.Value, 0, obs, oiml.idUsuario) Then

                MessageBox.Show("Registro grabado con exito!", "Pedidos", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                Me.DialogResult = Windows.Forms.DialogResult.OK
                CargarNota()

            Else
                MessageBox.Show("Error: " & controller.MessageError.Message, "Pedidos", MessageBoxButtons.OK, MessageBoxIcon.Error)

            End If

        End If

    End Sub

    Private Sub btneliminar_Click(sender As System.Object, e As System.EventArgs) Handles btneliminar.Click

        Try
            If codNota > 0 Then
                If MessageBox.Show("Desea eliminar el registro seleccionado?", "Pedidos", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                    If controller.Delete_Notas(oiml.dbConn, codNota, oiml.idUsuario) Then
                        Me.Close()

                    Else
                        MessageBox.Show("Error: " & controller.MessageError.Message, "Pedidos", MessageBoxButtons.OK, MessageBoxIcon.Error)

                    End If

                End If
            End If


        Catch ex As Exception
            MsgBox(ex.Message)

        End Try

    End Sub

    Private Sub txtcantidad_Leave(sender As System.Object, e As System.EventArgs)

        If ValidarDetallesCampos() Then
            txtcantidad.Focus()
        End If

    End Sub

    

    Private Sub cboTipoProducto_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs)
        If e.KeyCode = Keys.Enter Then
            CargarProductos()
        End If
    End Sub

    Private Sub txtProducto_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles txtProducto.KeyDown
        If e.KeyCode = Keys.Enter Then
            CargarProductos()
        End If
    End Sub

    Private Sub cboProducto_SelectedpValueChanged(sender As System.Object, e As System.EventArgs)

        SeleccionarProducto()

    End Sub

    Private Sub SeleccionarProducto()
        If Not cboProducto.SelectedValue Is Nothing Then
            If cboProducto.SelectedValue.ToString <> "System.Data.DataRowView" Then
                CargarProductos_ByID(cboProducto.SelectedValue)
            End If
        End If

    End Sub

    Private Sub CargarServicios_ByID(codServicio As Integer)

        Dim dt As New DataTable
        dt = servicios.get_Servicios_All(oiml.dbConn, codServicio, "", 0, True)

        If Not dt Is Nothing Then

            If IsNumeric(dt.Rows(0)("Precio").ToString()) Then
                txtPrecioServicio.Text = Decimal.Parse(dt.Rows(0)("Precio").ToString())

            Else
                txtPrecioServicio.Text = 0

            End If

        Else
            txtPrecioServicio.Text = 0

        End If

    End Sub

    Private Sub CargarProductos_ByID(codProducto As Integer)

        Dim dt As New DataTable
        dt = productos.get_Productos_All(oiml.dbConn, codProducto, "", 0, True)

        If Not dt Is Nothing Then

            If IsNumeric(dt.Rows(0)("PrecioVenta").ToString()) Then
                txtPrecio.Text = Decimal.Parse(dt.Rows(0)("PrecioVenta").ToString()).ToString("N0")

                llenarCombos_Actividad()

            Else
                txtPrecio.Text = 0

            End If

        Else
            txtPrecio.Text = 0

        End If

    End Sub

    

    Private m_frmRpts As FormReportes
    Public Property frmRpts() As FormReportes
        Get
            Return m_frmRpts
        End Get
        Set(value As FormReportes)
            m_frmRpts = value
        End Set
    End Property

    

    Private Sub tabControl_TabIndexChanged(sender As System.Object, e As System.EventArgs) Handles tabControl.TabIndexChanged

    End Sub

    Private Sub cboProducto_SelectedValueChanged(sender As System.Object, e As System.EventArgs) Handles cboProducto.SelectedValueChanged

        If IsNumeric(cboProducto.SelectedValue) Then
            CargarProductos_ByID(cboProducto.SelectedValue)
        End If


    End Sub

    Private Sub cboActividad_SelectedValueChanged(sender As System.Object, e As System.EventArgs) Handles cboActividad.SelectedValueChanged
        llenarCombos_Responsable()
        llenarCombos_Sector()
    End Sub

    Private Sub cboSector_SelectedValueChanged(sender As System.Object, e As System.EventArgs) Handles cboSector.SelectedValueChanged
        llenarCombos_Areas()

    End Sub

    
    Private Sub btnbuscarcli_Click(sender As System.Object, e As System.EventArgs) Handles btnbuscarcli.Click

        Dim frmBuscador As New BuscCliente
        frmBuscador.ShowDialog()
        codCliente = frmBuscador.codCliente
        txtNombre.Text = frmBuscador.nombreCliente
        txtRUC.Text = frmBuscador.rucCliente
        txtdireccion.Text = frmBuscador.direccCliente
        txtTelefono.Text = frmBuscador.telefCliente

        llenarCombos_ContactosCliente()

    End Sub

    Private Sub cboServicio_SelectedValueChanged(sender As System.Object, e As System.EventArgs) Handles cboServicio.SelectedValueChanged
        If IsNumeric(cboServicio.SelectedValue) Then
            CargarServicios_ByID(Integer.Parse(cboServicio.SelectedValue))
        End If

    End Sub

    Private Sub txtServicio_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles txtServicio.KeyDown
        If e.KeyCode = Keys.Enter Then
            If IsNumeric(cboServicio.SelectedValue) Then
                CargarServicios_ByID(Integer.Parse(cboServicio.SelectedValue))
            End If

        End If

    End Sub

    Private Sub cboTipoServicio_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles cboTipoServicio.KeyDown
        If e.KeyCode = Keys.Enter Then
            If IsNumeric(cboServicio.SelectedValue) Then
                CargarServicios_ByID(Integer.Parse(cboServicio.SelectedValue))
            End If

        End If

    End Sub

    Private Sub cbxTipoServicio_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles cbxTipoServicio.CheckedChanged
        If IsNumeric(cboServicio.SelectedValue) Then
            CargarServicios_ByID(Integer.Parse(cboServicio.SelectedValue))
        End If

    End Sub

    Private Sub cboTipoServicio_SelectedValueChanged(sender As System.Object, e As System.EventArgs) Handles cboTipoServicio.SelectedValueChanged

        CargarServicios()

    End Sub

    Private Sub cboTipoProducto_SelectedValueChanged_1(sender As System.Object, e As System.EventArgs) Handles cboTipoProducto.SelectedValueChanged
        CargarProductos()

    End Sub


    Private Sub cbxTipo_CheckedChanged_1(sender As System.Object, e As System.EventArgs) Handles cbxTipo.CheckedChanged
        CargarProductos()

    End Sub

    Private Sub txtobs_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtobs.TextChanged
        If tabControl.SelectedTab.Name = "tabProducto" Then
            txtObsServicio.Text = txtobs.Text

        End If

    End Sub

    Private Sub txtObsServicio_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtObsServicio.TextChanged
        If tabControl.SelectedTab.Name = "tabServicio" Then
            txtobs.Text = txtObsServicio.Text
        End If

    End Sub

    Private Sub btnAnular_Click(sender As System.Object, e As System.EventArgs) Handles btnAnular.Click
        Try
            If codNota > 0 Then
                If MessageBox.Show("Desea anular el registro seleccionado?", "Pedidos", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

                    If controller.Update_Notas_Estado(oiml.dbConn, codNota, oiml.codEstadoAnulaNota, oiml.idUsuario) Then
                        Me.Close()

                    Else
                        MessageBox.Show("Error: " & controller.MessageError.Message, "Pedidos", MessageBoxButtons.OK, MessageBoxIcon.Error)

                    End If

                End If
            End If


        Catch ex As Exception
            MsgBox(ex.Message)

        End Try

    End Sub

    Private Sub grpControles_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles grpControles.Enter

    End Sub
    Private Function imprimir() As DataTable
       
        Dim classController As New Class_RC_Controller.rc_Notas()
        Dim dt As New DataTable
        dt = classController.get_Notas_Imprimir(oiml.dbConn, codNota)

        If Not dt Is Nothing Then
            Return dt
        Else
            MessageBox.Show("Error: " & classController.MessageError.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return Nothing
        End If


    End Function

   
    Private Sub btnImprimir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImprimir.Click



        'Dim dt As New DataTable
        'dt = controller.get_Ventas_Producto_ByID(oiml.dbConn, codVenta)

        If frmRpts Is Nothing Then
            frmRpts = New FormReportes()
            'frmRpts.MdiParent = Me
            frmRpts.tipo_Reporte = "PEDIDO"
            frmRpts.datos_Reporte = imprimir()
            frmRpts.ShowDialog()
        Else

            If Not frmRpts.Visible Then
                frmRpts = New FormReportes()
                'frmRpts.MdiParent = Me
                frmRpts.tipo_Reporte = "PEDIDO"
                frmRpts.datos_Reporte = imprimir()
                frmRpts.ShowDialog()
            Else
                frmRpts.tipo_Reporte = "PEDIDO"
                frmRpts.datos_Reporte = imprimir()
                frmRpts.Select()
                frmRpts.Activate()
            End If

        End If

        If Not controller.MessageError Is Nothing Then
            MessageBox.Show("Error: " & controller.MessageError.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End If

    End Sub

    Private m_frmProducto As FrmProductos
    Public Property frmProductos() As FrmProductos
        Get
            Return m_frmProducto
        End Get
        Set(value As FrmProductos)
            m_frmProducto = value
        End Set
    End Property

    Private Sub btnNuevoProducto_Click(sender As System.Object, e As System.EventArgs) Handles btnNuevoProducto.Click
        frmProductos = New FrmProductos
        frmProductos.ShowDialog()
        CargarProductos()
    End Sub

End Class
